from tkinter import *
from tkinter import filedialog
from tkinter import ttk
from tkinter import font as tkfont
from threading import Thread
from mini_tools.cjjtool import *
from mini_tools.myexcel import *
from mini_tools.mytools import *
from sql import sqlseverDB
from config import *
import tkinter.messagebox as messagebox
import openpyxl,time,concurrent.futures



class ErrBidFra(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        LBFrame(self).pack(fill=X,padx=3,pady=3)

class LBFrame(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        Label(self, text='登录错误的店铺', fg="black", bg="yellow",font=("微软雅黑", 13)).pack(fill=X,padx=5)
        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)

        self.createWidgets()
        Thread(target=self.getCount).start()
        Thread(target=self.getmbData).start()
    def createWidgets(self):

        self.mbStr=StringVar()
        self.mbStr.set('正在获取今日错误店铺数量...')
        f2=Frame(self)
        f2.pack(fill=X,padx=2,pady=2)
        Label(f2, textvariable=self.mbStr,fg='red').pack(side=LEFT, padx=2, pady=2)
        self.mindc=None

        self.firstjz=True
        f0=Frame(self)
        f0.pack(fill=X,padx=2,pady=2)
        columns = ("bid","dpname","dpgroup","logintime","errdes")
        tree = ttk.Treeview(f0, show = "headings", columns = columns)
        tree.bind('<Double-1>', self.copy_to_clipboard)
        tree.column("bid", anchor = "center",width=80)
        tree.column("dpname", anchor = "center",width=150)
        tree.column("dpgroup", anchor = "center",width=150)
        tree.column("logintime", anchor = "center",width=150)
        tree.column("errdes", anchor = "center",width=220)


        tree.heading("bid", text = "浏览器id")
        tree.heading("dpname", text = "店铺名称")
        tree.heading("dpgroup", text = "店铺分组")
        tree.heading("logintime", text = "今日登录时间")
        tree.heading("errdes", text = "错误原因")
        
        self.VScroll1 = Scrollbar(f0, orient='vertical', command=tree.yview)
        self.VScroll1.pack(side=RIGHT,fill=Y)
        tree.configure(yscrollcommand=self.VScroll1.set)
        tree.pack(padx=3)
        self.tree=tree
        

        f1=Frame(self)
        f1.pack(fill=X,padx=2,pady=2)

        self.btn_catmb=Button(f1,text='刷新列表',command=lambda:Thread(target=self.upmb).start(),fg='#ffffff',bg='green',width=20)
        self.btn_catmb.pack(side=LEFT, padx=2, pady=2)
        self.btn_dc=Button(f1,text='导出列表',command=lambda:Thread(target=self.dc_err_list).start(),fg='#ffffff',bg='green',width=20)
        self.btn_dc.pack(side=RIGHT, padx=2, pady=2)

    

    def getCount(self):
        now = datetime.now()
        today_midnight = datetime(now.year, now.month, now.day)
        ct=int(today_midnight.timestamp())
        while True:
            try:
                rs0=self.ms.ExecQuery('select count(*) from errbid WHERE loginTime >= CAST(GETDATE() AS DATE)')
                self.mbStr.set(f'共有 {rs0[0][0]} 错误店铺')
                
            except Exception as e:
                print(e)
            time.sleep(10)

    def upmb(self):
        self.btn_catmb.config(state=DISABLED)
        self.getmbData()
        self.btn_catmb.config(state=NORMAL)
        
    def copy_to_clipboard(self,event):
        # 获取当前选择的项
        selected_item = self.tree.selection()
        if selected_item:
            # 获取选中项的值
            item = self.tree.item(selected_item)
            # 假设我们复制的是第一列的内容
            content = item['values'][0]
            # 将内容复制到剪贴板
            self.master.clipboard_clear()
            self.master.clipboard_append(content)
            print(f"成功复制内容: {content}")

    def getmbData(self):

        if not self.firstjz:
            for _ in map(self.tree.delete, self.tree.get_children("")):
                pass
        else:
            self.firstjz=False

        now = datetime.now()
        today_midnight = datetime(now.year, now.month, now.day)

        sqlstr=f'''
                select 
                bid,
                dpname,
                groupname,
                logintime,
                des
                from errbid join houtai on errbid.bid= houtai.browserid
                WHERE loginTime >= CAST(GETDATE() AS DATE)
     
            '''

        rs=ms.ExecQuery(sqlstr)
        i=1
        for v in rs:
            v[3]=str(v[3])[:-7]
            cv=list(v)
            cvalues=cv
            self.tree.insert('', i, values =cvalues)
            i += 1

    def dc_err_list(self):
        self.btn_dc.config(state=DISABLED)
        sqlstr=f'''
                select 
                bid 浏览器ID,
                dpname 店铺名字,
                groupname 店铺分组,
                logintime 登录时间,
                des 错误描述
                from errbid join houtai on errbid.bid= houtai.browserid
                WHERE loginTime >= CAST(GETDATE() AS DATE)
            '''
        fname=sqlToExcel('错误的店铺',self.ms,sqlstr)

        self.btn_dc.config(state=NORMAL)


# import tkinter
# list_win=tkinter.Tk()
# list_win.wm_geometry("800x650")
# list_win.title('错误的店铺')
# ErrBidFra(list_win).pack(fill=X,padx=3,pady=3)
# list_win.mainloop()